﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;

namespace Tesla.Graphics {
    
    /// <summary>
    /// Represents a list of vertices that exists on the GPU. A vertex typically has a position
    /// and a number of additional properties such as a color or normal vector.
    /// </summary>
    public class VertexBuffer : GraphicsResource, ISavable {
        private VertexBufferImplementation _impl;


        /// <summary>
        /// Gets the API-specific implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets the vertx declaration that describes the type of data contained in
        /// this buffer.
        /// </summary>
        public VertexDeclaration VertexDeclaration {
            get {
                return _impl.VertexDeclaration;
            }
        }

        /// <summary>
        /// Gets the number of vertices in this buffer.
        /// </summary>
        public int VertexCount {
            get {
                return _impl.VertexCount;
            }
        }

        /// <summary>
        /// Gets the resource usage of the buffer, either static or dynamic.
        /// </summary>
        public ResourceUsage BufferUsage {
            get {
                return _impl.BufferUsage;
            }
        }

        /// <summary>
        /// For ISavable.
        /// </summary>
        protected VertexBuffer() {}

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="declaration">Vertex declaration that defines the vertex data this buffer will contain</param>
        /// <param name="vertexCount">Number of vertices the buffer will contain</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails or the render system
        /// was not initialized.</exception>
        public VertexBuffer(VertexDeclaration declaration, int vertexCount, ResourceUsage usage) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, vertexCount, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="declaration">Vertex declaration that defines the vertex data of this buffer</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <param name="data">Vertex store arrays, one for each vertex element of the vertex declaration</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating or writing to the underlying buffer fails or
        /// the render system was not initialized.</exception>
        public VertexBuffer(VertexDeclaration declaration, ResourceUsage usage, params DataBuffer[] data) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, usage, data);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="declaration">Vertex declaration that defines the vertex data of this buffer</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <param name="data">Vertex data</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating or writing to the underlying buffer fails or the render
        /// system was not initialized.</exception>
        public VertexBuffer(VertexDeclaration declaration, ResourceUsage usage, DataBuffer data) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, usage, data);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="declaration">Vertex declaration that defines the vertex data this buffer will contain</param>
        /// <param name="vertexCount">Number of vertices the buffer will contain</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails.</exception>
        public VertexBuffer(IRenderSystemProvider renderSystem, VertexDeclaration declaration, int vertexCount, ResourceUsage usage) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="declaration">Vertex declaration that defines the vertex data of this buffer</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <param name="data">Vertex store arrays, one for each vertex element of the vertex declaration</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating or writing to the underlying buffer fails.</exception>
        public VertexBuffer(IRenderSystemProvider renderSystem, VertexDeclaration declaration, ResourceUsage usage, params DataBuffer[] data) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, usage, data);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="declaration">Vertex declaration that defines the vertex data of this buffer</param>
        /// <param name="usage">Buffer usage, either static or dynamic</param>
        /// <param name="data">Vertex data</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating or writing to the underlying buffer fails.</exception>
        public VertexBuffer(IRenderSystemProvider renderSystem, VertexDeclaration declaration, ResourceUsage usage, DataBuffer data) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(declaration, usage, data);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="VertexBuffer"/> is reclaimed by garbage collection.
        /// </summary>
        ~VertexBuffer() {
            Dispose(false);
        }

        /// <summary>
        /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order
        /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match
        /// the vertex declaration as well as the byte sizes of each element and all be of the same length.
        /// </summary>
        /// <param name="data">Array of databuffers representing the vertex data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the number of data buffers do not match
        /// the number of vertex elements declared in the vertex buffer.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetInterleavedData(params DataBuffer[] data) {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            if(data.Length != _impl.VertexDeclaration.VertexElements.Length) {
                throw new ArgumentOutOfRangeException("Number of buffers do not match the number of declared vertex elements.");
            }

            try {
                _impl.SetInterleavedData(data);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, data.Length, 0, 0, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, data.Length, 0, 0, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, 0, 0, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, 0, 0, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the buffer or
        /// arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
            _impl.SetData<T>(data, startIndex, elementCount, offsetInBytes, vertexStride, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes.</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, offsetInBytes, vertexStride, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, 0, data.Length, 0, 0);
            } catch(Exception e) {
                throw new TeslaException("Error reading from vertex buffer: \n" + e.Message, e);
            }
        }


        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <param name="startIndex">Index of the element in the array at each to start writing to</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, startIndex, elementCount, 0, 0);
            } catch(Exception e) {
                throw new TeslaException("Error reading from vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <param name="startIndex">Index of the element in the array at each to start writing to</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the vertex buffer
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, startIndex, elementCount, offsetInBytes, vertexStride);
            } catch(Exception e) {
                throw new TeslaException("Error reading from vertex buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public void Write(ISavableWriter output) {
            output.Write("Name", base.Name);
            output.WriteSavable<VertexDeclaration>("VertexDeclaration", _impl.VertexDeclaration);
            output.Write("VertexCount", _impl.VertexCount);
            output.WriteEnum<ResourceUsage>("BufferUsage", _impl.BufferUsage);
            byte[] byteBuffer = new byte[_impl.VertexDeclaration.VertexStride * _impl.VertexCount];
            GetData<byte>(byteBuffer);
            output.Write("VertexData", byteBuffer);
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying implementation fails or the render
        /// system is not set.</exception>
        public void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            String name = input.ReadString();
            VertexDeclaration decl = input.ReadSavable<VertexDeclaration>();
            int vertexCount = input.ReadInt();
            ResourceUsage usage = input.ReadEnum<ResourceUsage>();
            byte[] byteBuffer = input.ReadByteArray();

            try {
                _impl = renderSystem.CreateVertexBufferImplementation(decl, vertexCount, usage);
                _impl.Name = name;
                SetData<byte>(byteBuffer);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }
    }
}
